//
//  ViewController.m
//  CheckSN
//
//  Created by Kirby on 2025/8/25Monday.
//

#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _scanSNTextField.delegate = self;
    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"SN" ofType:@"csv"];
    _SNSet = [self loadSNSetFromCSV:filePath];
    // Do any additional setup after loading the view.
}


- (void)setRepresentedObject:(id)representedObject {
    [super setRepresentedObject:representedObject];
    
    // Update the view, if already loaded.
}

- (void)checkSN{
    // 使用示例
    dispatch_async(dispatch_get_main_queue(), ^ {
        self.SNTextField.stringValue = self.scanSNTextField.stringValue;
        self.scanSNTextField.stringValue = @"";
        NSString *targetSN = self.SNTextField.stringValue;
        
        if (self.SNSet && [self.SNSet containsObject:targetSN]) {
            NSLog(@"SN存在");
            self.resultTextField.stringValue = @"NG";
            self.resultTextField.backgroundColor = [NSColor redColor];
        } else {
            NSLog(@"SN不存在");
            self.resultTextField.stringValue = @"PASS";
            self.resultTextField.backgroundColor = [NSColor greenColor];
        }
    });
    
}

- (NSSet *)loadSNSetFromCSV:(NSString *)filePath {
    NSError *error = nil;
    NSString *fileContents = [NSString stringWithContentsOfFile:filePath
                                                      encoding:NSUTF8StringEncoding
                                                         error:&error];
    
    if (error) {
        NSLog(@"读取文件错误: %@", error);
        return nil;
    }
    
    NSMutableSet *snSet = [NSMutableSet set];
    NSArray *lines = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
    
    for (NSString *line in lines) {
        if (line.length == 0) continue;
        [snSet addObject:line];
    }
    
    return [snSet copy];
}

- (BOOL)control:(NSControl *)control textView:(NSTextView *)textView doCommandBySelector:(SEL)commandSelector{
    if ([NSStringFromSelector(commandSelector) isEqualToString:@"insertNewline:"]) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
            [self checkSN];
        });
    }
    return NO;
}
@end
